package com.example.springmvc_adv.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @ClassName LoginInterceptor
 * @Description TODO
 * @Author H.
 * @Date 2023/4/27 21:22
 * @Version 1.0
 */
//HandlerInterceptor专门实现请求响应的拦截器

public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 请求前拦截
     * @param request Servlet的请求
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session，如果获取不到，则返回为null
        HttpSession session = request.getSession(false);
        if(session != null){
            String user = (String) session.getAttribute("user");
            //如果session以及session中保存的用户不能为空，那么就证明已经登录
            if(user != null){
                return true;
            }
        }
        //没有session 不允许访问
        response.setStatus(401);
        return false;
    }
}
